package Synchronized_1;
class TicketSeller {
    private int tickets = 100;
    private Object lock = new Object();//没用static，因为这个类只被创建了一个对象，所有线程共享

    public void sellTicket() {
        synchronized(lock) {//此处也可也用TicketSeller.class
            if (tickets > 0) {
                try {
                    Thread.sleep(20); // 模拟出票时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()
                                           + " 售出第 " + tickets-- + " 张票");
            } else {
                System.out.println("票已售罄");
            }
        }
    }
}

public class 同步代码块{
    public static void main(String[] args) {
        final TicketSeller seller = new TicketSeller();

        // 创建50个购票线程
        for (int i = 0; i < 200; i++) {
            new Thread(new Runnable() {
                public void run() {
                    seller.sellTicket();//
                }
            }, "购票者-" + i).start();
        }
    }
}